package com.taptech.doufu.ui.activity.me
import android.app.Activity
import android.content.Context
import android.content.Intent
import android.graphics.Paint
import android.os.Bundle
import android.view.View
import android.widget.Toast
import androidx.recyclerview.widget.GridLayoutManager
import com.google.android.material.bottomsheet.BottomSheetDialog
import com.taptech.doufu.R
import com.taptech.doufu.alipay.AliPayActivity
import com.taptech.doufu.event.EventBusPayResult
import com.taptech.doufu.net.retrofit.RxBus
import com.taptech.doufu.net.retrofit.api.RxJavaHelper
import com.taptech.doufu.ui.activity.BrowseActivity
import com.taptech.doufu.ui.activity.base.DiaobaoBaseActivity
import com.taptech.doufu.ui.activity.weex.SimpleWeexActivity
import com.taptech.doufu.ui.adapter.BaseRecyclerAdappter
import com.taptech.doufu.ui.adapter.CoinOptionAdapter
import com.taptech.doufu.ui.dialog.DoubleBtnTiptDialog
import com.taptech.doufu.ui.view.WaitDialog
import com.taptech.doufu.util.GsonUtil
import com.taptech.doufu.weex.http.TFHttpUtil
import com.douhuayuedu.douhua.wxapi.WeixinService
import kotlinx.android.synthetic.main.activity_my_coin.*

class MyCoinActivity:DiaobaoBaseActivity() {

    var baseTicket = VoucherActivity.VoucherBean()
    var ticketCount = 0
    var currCoinOption:CoinOption = CoinOption()
    var selectTicketId = 0
    var selectAmount = 0f
    lateinit var waitDialog: WaitDialog

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_my_coin)
        waitDialog = WaitDialog(this,R.style.updateDialog)
        waitDialog.show()
        getOptions()
        tvMoreWay.setOnClickListener {
            BrowseActivity.startActivity(this,"http://api.doufu.la/index.php/journal/detail?id=341")
        }
        ivHelp.setOnClickListener {
            BrowseActivity.startActivity(this,"https://api.doufu.la/index.php/help/question/type?id=10")
        }
        layCoinInfo.setOnClickListener {
            SimpleWeexActivity.startActivity(this,"vue/personalcenter/TFMyCoinInfo.js")
        }
        layPay.setOnClickListener {
            toastDialog()
        }
        layVoucher.setOnClickListener {
            VoucherActivity.startActivityForResult(this,false,optionId = currCoinOption.id,ticketId = selectTicketId)
        }
        RxBus.getDefault()
                .toObservable(EventBusPayResult::class.java)
                .onBackpressureBuffer()
                .compose(RxJavaHelper.observeOnMainThread())
                .subscribe { it ->
                    if (it.isSuccess) {
                        getOptions()
                    }
                    if (it.msg != null) {
                        Toast.makeText(thisActivity,it.msg,Toast.LENGTH_LONG).show()
                    }
                }
    }


    fun getOptions() {
        val url = "http://api.doufu.la/getAppPayOptions"
        TFHttpUtil.requestGet(url,null){json, error ->
            try {
                val data = json.getJSONObject("data")
                val list = GsonUtil.jsonToList(data.getJSONArray("list").toJSONString(), Array<CoinOption>::class.java)
                val coinInfo = GsonUtil.parseJsonWithGson(data.getJSONObject("coinInfo").toJSONString(),CoinInfo::class.java)
                var firstRecharge = data.getIntValue("firstRecharge")
                tvCoin.text = coinInfo.coin
                initOption(list,firstRecharge)
            } catch (e: Exception) {
                e.printStackTrace()
            }
            waitDialog.dismiss()
        }
    }

    fun getSelectTicket(optionId:Int) {
        val  url = "http://api.doufu.la/getMyCashTicketUsableCount"
        val params = mutableMapOf<String,Any>()
        params["option_id"] = optionId
        TFHttpUtil.requestGet(url,params){json, error ->
            try {
                val data = json.getJSONObject("data")
                ticketCount = data.getIntValue("total")
                baseTicket = GsonUtil.parseJsonWithGson(data.getJSONObject("bestCashTicket").toJSONString(),VoucherActivity.VoucherBean::class.java)
            } catch (e: Exception) {
                e.printStackTrace()
                baseTicket = VoucherActivity.VoucherBean()
            }
            selectTicketId = baseTicket.id
            selectAmount = baseTicket.amount
            updateUi()
        }
    }


    fun toastDialog() {
        val dialog = BottomSheetDialog(thisActivity)
        dialog.setContentView(R.layout.dialog_pay)
        dialog.findViewById<View>(R.id.layWX)?.setOnClickListener {
            getWXPayData()
            dialog.dismiss()
        }
        dialog.findViewById<View>(R.id.layAli)?.setOnClickListener {
            getAliPayData()
            dialog.dismiss()
        }
        dialog.findViewById<View>(R.id.layDoufu)?.setOnClickListener {
            toastWarnDialog()
            dialog.dismiss()
        }
        dialog.findViewById<View>(R.id.layMore)?.setOnClickListener {
            BrowseActivity.startActivity(this, "https://api.doufu.la/journal/detail?id=121")
            dialog.dismiss()
        }
        dialog.show()
    }

    fun toastWarnDialog() {
        val dialog = DoubleBtnTiptDialog(this,R.style.updateDialog,
                "确定要使用收入充值豆币吗？","确定", DoubleBtnTiptDialog.CallBack {
            payIncome()
        })
        dialog.show()
    }


    fun getWXPayData() {
        waitDialog.show()
        val url = "http://api.doufu.la/pay_init/coin/wx"
        val params = mutableMapOf<String,Any>()
        params["option_id"] = currCoinOption.id
        if (selectTicketId > 0) {
            params["cash_ticket_id"] = selectTicketId
        }
        TFHttpUtil.requestGet(url,params){json, error ->
            try {
                val data = json.getJSONObject("data")
                WeixinService.getInstance(this).payRequest(data.getJSONObject("config").toJSONString())
            } catch (e: Exception) {
                e.printStackTrace()
            }
            waitDialog.dismiss()
        }
    }

    fun getAliPayData() {
        waitDialog.show()
        val url = "https://api.doufu.la/pay_init/coin/alipay"
        val params = mutableMapOf<String,Any>()
        params["option_id"] = currCoinOption.id
        if (selectTicketId > 0) {
            params["cash_ticket_id"] = selectTicketId
        }
        TFHttpUtil.requestGet(url,params){json, error ->
            try {
                val data = json.getJSONObject("data")
                AliPayActivity.startActivity(this, data.getString("config"))
            } catch (e: Exception) {
                e.printStackTrace()
            }
            waitDialog.dismiss()
        }
    }


    fun payIncome() {
        waitDialog.show()
        val url = "https://api.doufu.la/index.php/user_coin/income2doubi"
        val params = mutableMapOf<String,Any>()
        params["amount"] = currCoinOption.amount
        if (selectTicketId > 0) {
            params["cash_ticket_id"] = selectTicketId
        }
        TFHttpUtil.requestPost(url,params){json, error ->
            try {
                val data = json.getJSONObject("data")
                if (data != null && data.size > 0) {
                    val success = data.getIntValue("success")
                    if (success == 1) {
                        Toast.makeText(thisActivity, "充值成功", Toast.LENGTH_LONG).show()
                        getOptions()
                    } else {
                        val msg = data.getString("msg")
                        if (msg != null) {
                            Toast.makeText(thisActivity, msg, Toast.LENGTH_LONG).show()
                        } else {
                            Toast.makeText(thisActivity, "充值失败", Toast.LENGTH_LONG).show()
                        }
                    }
                } else {
                    val user_mag = json.getString("user_msg")
                    if (user_mag != null) {
                        Toast.makeText(thisActivity, user_mag, Toast.LENGTH_LONG).show()
                    }
                }

            } catch (e: Exception) {
                e.printStackTrace()
            }
            waitDialog.dismiss()
        }
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (resultCode == Activity.RESULT_OK) {
            if (data == null) {
                return
            }
            selectTicketId = data.getIntExtra(VoucherActivity.INTENT_KEY_TICKET_ID,0)
            selectAmount = data.getFloatExtra(VoucherActivity.INTENT_KEY_AMOUNT,0f)
            updateUi()
        }
    }

    private fun updateUi() {
        tvPay.text = "立即支付￥${currCoinOption.amount/100-baseTicket.amount/100}"
        tvTotalPrice.paintFlags = Paint.STRIKE_THRU_TEXT_FLAG
        if (ticketCount == 0) {
            //显示暂无
            tvNone.visibility = View.VISIBLE
            tvTicketAmount.visibility = View.GONE
            tvTicketCount.visibility = View.GONE
            tvTotalPrice.visibility = View.GONE
        }else{
            tvNone.visibility = View.GONE
            if (selectAmount > 0) {
                tvTotalPrice.visibility = View.VISIBLE
                tvTicketAmount.visibility = View.VISIBLE
                tvTicketCount.visibility = View.GONE
                tvTicketAmount.text = "-￥${selectAmount / 100}"
                tvTotalPrice.text = "原价￥${currCoinOption.amount / 100}"
            } else {
                tvTotalPrice.visibility = View.GONE
                tvTicketCount.visibility = View.VISIBLE
                tvTicketAmount.visibility = View.GONE
                tvTicketCount.text = "${ticketCount}个可用"
            }
        }
    }

    fun initOption(list: MutableList<CoinOption>,firstRecharge:Int){
        if (list.size>3){
            list[3].select = true
            getSelectTicket(list[3].id)
            currCoinOption = list[3]
        }
        val adapter = CoinOptionAdapter(this,firstRecharge)
        adapter.setOnItemClickListener(object :BaseRecyclerAdappter.OnItemClickListener<CoinOption>{
            override fun onClick(item: CoinOption, position: Int) {
                adapter.dataList.forEachIndexed { index, coinOption ->
                    coinOption.select = position == index
                }
                adapter.notifyDataSetChanged()
                currCoinOption = item
                getSelectTicket(item.id)

            }
        })
        mRecyclerView.layoutManager = GridLayoutManager(this,2)
        mRecyclerView.adapter = adapter
        adapter.setData(list)
    }


    data class CoinOption(
            val id:Int = 0,
            val coin:Int = 0,
            val amount:Int = 0,
            val tip:String = "",
            val product_id:String = "",
            val read_ticket:Int = 0,
            val txt:String = "",
            var select:Boolean = false
    )

    data class CoinInfo(
            val user_id:Int = 0,
            val status:Int = 0,
            val coin:String = "",
            val cas:String = "",
            val created_at:String = "",
            val updated_at:String = ""
    )

    companion object{
        fun startActivity(context: Context?) {
            val intent = Intent(context,MyCoinActivity::class.java)
            context?.startActivity(intent)
        }
    }
}